package com.felight.sql;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

import java.sql.Connection;


public class ConnectionFactory{
	private static Logger log = Logger.getLogger(ConnectionFactory.class);
	private static ConnectionFactory instance = new ConnectionFactory();
	private Properties prop = new Properties();
	private static String url;
	private static String userName;
	private static String password;
	private static String driver;
	private static Connection connection;
	
	public static Connection getConnection(){
		return instance.createConnection();
	}
	private Connection createConnection(){
		try{
			connection = DriverManager.getConnection(url,userName,password);
		}
		catch(SQLException e){
			log.error("ERROR: Unable to Connect to database");
			log.error(e);
		}
		return connection;
	}
	private ConnectionFactory(){
		initialize();
	}
	private void initialize(){
		try{
			prop.load(new FileInputStream("application.properties"));
			url = prop.getProperty("url");
			userName = prop.getProperty("username");
			password = prop.getProperty("password");
			driver = prop.getProperty("driver");
			Class.forName(driver);
			log.info("Using Driver :"+ driver);
			log.info("Driver registration successfull");
		}
		catch(FileNotFoundException e){
			System.out.println("file not found");
			log.error("application.properties file not found");
			log.error(e);
		}
		catch(IOException e){
			log.error("Error occured while reading application.properties"
					+ "please check if the file has write access or not");
			log.error(e);
		}
		catch(ClassNotFoundException e){
			log.error("driver initialization failed");
			log.error(e);
		}
	}
}


